package com.vcredit.creditcat.framework.util;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
/**
 * json工具类
 *
 */
public class JsonUtil {
	/**
	 * 返回JSON字符串
	 * @param keyVaues 生成JSON的键值对
	 * @return
	 */	
	public static String getJsonStr(Object ... keyValues) {
		int length = keyValues.length;
		JSONObject json = new JSONObject();
		
		if (length % 2 == 0) {
			for (int i = 0; i < length; i+=2) {
				json.put(keyValues[i].toString(), keyValues[i + 1]);
			}
		}
		
		return json.toString();
	}
	/**
	 * 返回JSON字符串
	 * @param key 生成JSON的KEY
	 * @param val 生成JSON的VALUE
	 * @return
	 */
	public static String getJsonStr(String key, Object val){
		JSONObject json = new JSONObject();
		json.put(key, val);
		return json.toString();
	}
	/**
	 * 根据MAP和自定义CONFIG来生成JSON字符串
	 * @param map 生成字符串所需集合
	 * @param config 自定义配置
	 * @return
	 */
	public static String getJsonStr(Map<String,Object> map, JsonConfig config){
		JSONObject json = new JSONObject();
		if(config!=null)
			json.putAll(map, config);
		else
			json.putAll(map);
		return json.toString();
	}
	
	public static String getJsonStr(Map<String, Object> map){
		return getJsonStr(map, null);
	}
	
	 /**
	  * 从一个JSON 对象字符格式中得到一个java对象
	  * @param jsonString
	  * @param clazz
	  * @return
	  */
	@SuppressWarnings("unchecked")
	public static <T> T getDTO1(String jsonString, Class<T> clazz){ 
		JSONObject jsonObject = null; 
		try{ 
			jsonObject = JSONObject.fromObject(jsonString);
		}catch(Exception e){ 
			e.printStackTrace(); 
		} 
		return (T)JSONObject.toBean(jsonObject, clazz); 
	}
	/**
	 * @param obj
	 * @return
	 */
	public static String Obj2Json(Object obj) {
		try {
			ObjectMapper objectMapper = new ObjectMapper();
			String json = objectMapper.writeValueAsString(obj);

			return json;
		} catch (IOException e) {
			e.printStackTrace();

			return "";
		}
	}
	/**
	 * 把数据对象转换成json字符串
	 * @param object
	 * @return
	 * @throws Exception
	 */
	public static String getJSONString(Object object){ 
		String jsonString = null; 
		//日期值处理器 
		JsonConfig jsonConfig = new JsonConfig(); 
		if(object != null){ 
			if(object instanceof Collection || object instanceof Object[]){ 
				jsonString = JSONArray.fromObject(object, jsonConfig).toString(); 
			}else{ 
				jsonString = JSONObject.fromObject(object, jsonConfig).toString(); 
			} 
		} 
		return jsonString == null ? "{}" : jsonString; 
	} 
	
	@SuppressWarnings("unchecked")
	public static <T> List<T> getJSONObject(String str, Class<T> clazz){
		JSONArray jsonarray = JSONArray.fromObject(str);   
		return (List<T>)JSONArray.toCollection(jsonarray,clazz);   
	}
}
